<template>
  <!-- 放置一个弹层 用来编辑新增节点 -->
  <el-dialog :title="`${showText}角色`" :visible.sync="showDialog" @close="btnCancel">
    <!-- 表单 -->
    <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="角色名称" prop="role_name">
        <el-input v-model="formData.role_name" style="width:90%" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色标识" prop="identify">
        <el-input v-model="formData.identify" style="width:90%" placeholder="请输入角色标识" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" style="width:90%" placeholder="请输入角色描述" />
      </el-form-item>
      <el-form-item label="角色权限" prop="authlist">
        <el-tree
          ref="tree"
          :data="listdata"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          :default-expanded-keys="arrdata"
        />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        <el-button size="small" @click="showDialog=false">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import { getInfolist, addyhlist, xgyhlist, yonghujsxq, yonghuqxlist } from '@/api/user'
export default {
  name: 'Addjs',
  data() {
    const checkRepeatName = async(rules, value, cb) => {
      let isRepeat = false
      if (this.formData.id) {
        // 修改  思路：找到我的兄弟们(pid相同)，除了我之外，还有兄弟和我同名，说明就重复了
        isRepeat = this.list.filter(item => item.id !== this.formData.id).some(item => item.role_name === value)
      } else {
      //   // 添加  思路： 找到当前点击部门的子部门数据； 将输入的值和这些子部门数据的name进行匹配，找到说明存在了
        isRepeat = this.list.some(item => item.role_name === value)
      }
      return isRepeat ? cb(new Error(`同级已经存在${value}这个名称`)) : cb()
    }
    const checkidentify = async(rules, value, cb) => {
      let isRepeat = false
      if (this.formData.id) {
        // 修改  思路：找到我的兄弟们(pid相同)，除了我之外，还有兄弟和我同名，说明就重复了
        isRepeat = this.list.filter(item => item.id !== this.formData.id).some(item => item.identify === value)
      } else {
      //   // 添加  思路： 找到当前点击部门的子部门数据； 将输入的值和这些子部门数据的name进行匹配，找到说明存在了
        isRepeat = this.list.some(item => item.identify === value)
      }
      return isRepeat ? cb(new Error(`同级已经存在${value}这个标签`)) : cb()
    }
    return {
      formData: {},
      showDialog: false,
      defaultProps: {
        children: 'children',
        label: 'permission_name'
      },
      rules: {
        role_name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' },
          { validator: checkRepeatName, trigger: 'blur' }],
        identify: [{ required: true, message: '角色标识不能为空', trigger: 'blur' },
          { validator: checkidentify, trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }],
        authlist: []
      },
      listdata: {},
      defaultChecked: [],
      authlist: [],
      roleId: null,
      arrdata: [],
      list: []
    }
  },
  computed: {
    showText() {
      return this.formData.id ? '修改' : '添加'
    }
  },
  watch: {
    // 监听页面打开和关闭
    showDialog: {
      deep: true,
      handler() {
        if (this.showDialog === false) {
          this.formData = {}
          this.arrdata = []
          this.$refs.tree.setCheckedKeys([])
          // console.log(this.$refs.tree)
          this.showDialog = false
        }
      }
    }
  },
  created() {
    this.getInfo()
  },
  methods: {
    async getInfo() {
      const res = await getInfolist()
      const { data } = await yonghuqxlist()
      this.list = data.list
      console.log(this.list)
      this.listdata = res.data
    },
    // 获得点击的id，获取用户信息
    async getSingleInfo(id) {
      const { data } = await yonghujsxq(id)
      this.formData = data
      this.formData.id = data.id
      this.digui(data.authlist)
      this.$refs.tree.setCheckedKeys(this.arrdata)
      // console.log(this.arrdata)
    },
    // 递归，回显
    digui(val) {
      val.forEach((item) => {
        if (!item.children) {
          this.arrdata.push(item.id)
          return
        }
        return this.digui(item.children)
      })
    },

    // async getRoleAuth(id) {
    //   this.roleId = id
    // const { permIds } = await getRoleInfoData(id)
    // this.defaultChecked = permIds
    // },
    // 确定添加或修改
    async btnOK() {
      // const checkKeys = {
      //   ...this.$refs.tree.getCheckedKeys(),
      //   ...this.$refs.tree.getHalfCheckedKeys()
      // }
      const res1 = this.$refs.tree.getCheckedKeys()
      const res2 = this.$refs.tree.getHalfCheckedKeys()
      const permIds = [...res1, ...res2]
      if (permIds.length === 0) return this.$message.warning('请勾选节点')
      // 校验数据
      await this.$refs.perForm.validate()
      // 发送请求
      if (this.formData.id) {
        this.formData.authlist = permIds
        await xgyhlist(this.formData.id, this.formData)
      } else {
        await addyhlist({
          role_name: this.formData.role_name,
          identify: this.formData.identify,
          description: this.formData.description,
          authlist: permIds
        })
      }
      // 提示成功
      this.$message.success(this.formData.id ? '修改成功' : '添加成功')
      // 关闭
      this.showDialog = false
      // 列表更新
      this.$emit('update-list')
    },
    // 关闭页面，清理数据
    btnCancel() {
      this.formData = {}
      this.arrdata = []
      this.$refs.tree.setCheckedKeys([])
      this.showDialog = false
    }
  }

}
</script>

<style>

</style>
